#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/6/5 下午4:34
# @Author  : Huang-Bo
import time
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.executors.pool import ProcessPoolExecutor
from datetime import datetime
import pandas as pd
from utils.ecs_inspection_script import EcsInspection, generate_report
from utils.config_loader import load_config
from utils.logger import setup_logger
from utils.msg_notice import WechatNotifier
from utils.clean_local_report_file import clean_old_reports

# -------------基础配置---------------
config = load_config()
success_logger = setup_logger("success", config["log"]["success_log"], level="INFO")
error_logger = setup_logger("error", config["log"]["error_log"], level="ERROR")
report_dir = config["report"]["path"]
notifier = WechatNotifier(
    webhook_url=config["wechat"]["webhook_url"],
    upload_url=config["wechat"]["upload_url"])


def main():
    start = time.time()
    # 创建 EcsInspection 对象
    inspector = EcsInspection()
    data = inspector.collect_inspection_data()

    if data.empty:
        error_logger.warning("未获取到巡检数据，终止巡检流程")
        return
    # 巡检报告生成路径
    report_file = f"{report_dir}/ecs_inspection_report_{datetime.now().strftime('%Y%m%d%H%M%S')}.xlsx"
    # 生成巡检报告
    generate_report(data, report_file)
    # 分别统计CPU、内存、磁盘 使用率超出阈值的机器数量
    usage_cols = [col for col in data.columns if any(k in col for k in ['CPU', '内存', '磁盘'])]
    usage = data[usage_cols].apply(pd.to_numeric, errors='coerce')

    # 按指标类型分组统计
    metrics_results = {}
    for metric in ['CPU', '内存', '磁盘']:
        metric_cols = [col for col in usage.columns if metric in col]
        metric_data = usage[metric_cols]
        warn_count = ((metric_data >= 75) & (metric_data <= 80)).sum().sum()
        critical_count = (metric_data > 80).sum().sum()
        metrics_results[metric] = {
            'warn': warn_count,
            'critical': critical_count,
            'total': len(metric_data)  # 添加总数用于计算百分比
        }
    msg = f"""
    ## 🛠️  ECS资源巡检报告\n\n
    ### 巡检概览
    > ⏰ 时间：<font color='comment'>{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</font>
    > ⏱️ 耗时：<font color='comment'>{round(time.time() - start, 2)}秒</font>
    > 🖥️ 总数：<font color='comment'>{len(data)}台</font>\n
    #### CPU使用率
    > 警告：<font color='warning'>{metrics_results['CPU']['warn']}</font>台
    > 严重：<font color='red'>{metrics_results['CPU']['critical']}</font>台\n
    #### 内存使用率
    > 警告：<font color='warning'>{metrics_results['内存']['warn']}</font>台
    > 严重：<font color='red'>{metrics_results['内存']['critical']}</font>台\n
    #### 磁盘使用率
    > 警告：<font color='warning'>{metrics_results['磁盘']['warn']}</font>台
    > 严重：<font color='red'>{metrics_results['磁盘']['critical']}</font>台\n\n
<font color='#888'>注：75-80%为警告范围 80%以上为异常范围</font>
<font color='#888'>详细数据请查看附件报告</font>
    """
    try:
        notifier.send_markdown_msg("阿里云ECS资源巡检报告通知", msg)
        notifier.send_file_msg(report_file)
    except Exception as e:
        error_logger.error(f"通知发送失败: {e}")
    finally:
        # 删除本地生成的报告文件
        clean_old_reports(report_dir=report_dir, days_to_keep=7)


if __name__ == '__main__':
    executors = {
        'default': ProcessPoolExecutor(1)
    }
    job_defaults = {
        'coalesce': True,  # 合并执行
        'max_instances': 1,  # 最大实例数
        'misfire_grace_time': 3600  # 错过执行的宽限时间
    }
    scheduler = BackgroundScheduler(
        executors=executors,
        job_defaults=job_defaults
    )
    # 每隔1分钟执行一次
    scheduler.add_job(main, trigger='cron', minute='*/1')
    try:
        scheduler.start()
        while True:
            time.sleep(1)
    except (KeyboardInterrupt, SystemExit):
        scheduler.shutdown()
